package com.hua.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewFilter;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration

public class DruidConfig {



    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druid(){
        return new DruidDataSource();
    }

    //后台监控功能  web.xml ServletRegistrationBean
    // 因为spring-boot  内置了   Servlet容器 所以没有web.xml 替代方法 将 ServletRegistrationBean 注册到容器
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登录 配置账号密码
        Map<String, String> initParameters = new HashMap<String, String>();
        //登录的 key-name  是固定的
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "admin");
        //允许谁能访问        ip地址
//        initParameters.put("allow", "");
        //禁止谁能访问  ip地址  initParameters.put("deny", "");

        //初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }

    //filter  过滤
    @Bean
    public FilterRegistrationBean registrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //排除那些请求
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        return bean;
    }


}
